import React from 'react';
import { Breadcrumb, Icon, Table, Button, Modal, Form, Input, Upload, message } from 'antd';
import './floor.less';
import $ from 'jquery';
import Config from '../../common/config';
import FloorProduct from './floorProduct';
import { Col } from 'antd/lib/grid';

const config = new Config();
const FormItem = Form.Item;
const { TextArea } = Input;
const token = sessionStorage.getItem('token')

//楼层信息的表单
const FloorForm = Form.create()(
    (props) => {
        const { form, normFile, beforeUpload, fileList, previewImg } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 17 }, };
        return (
            <Form layout="vertical">
                <FormItem {...formItemLayout} label="楼层名称" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                    {getFieldDecorator('floorname', {
                        rules: [{ required: true, max: 6, message: '请输入楼层名称，不超过6个字' }],
                    })(
                        <Input type="text" placeholder="请输入楼层名称" />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="链接地址" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                    {getFieldDecorator('link', {
                        rules: [{ required: true, message: '请输入链接地址' }],
                    })(
                        <Input type="text" placeholder="请输入链接地址" />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="楼层描述" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                    {getFieldDecorator('description', {
                        rules: [{ required: true, max: 50, message: '请输入楼层描述，不超过50个字' }],
                    })(
                        <TextArea placeholder="请输入楼层描述" rows={3} style={{ resize: "none" }} />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="主题图片" style={{ minHeight: '120px', marginBottom: 0 }}>
                    {getFieldDecorator('Filedata', {
                        valuePropName: 'fileList', getValueFromEvent: normFile,
                        rules: [{ required: true, message: '请上传主题图片' }],
                    })(<Upload
                        accept="image/*"
                        name='img'
                        action={config.UploadFile + "/img"}
                        beforeUpload={beforeUpload}
                        listType="picture-card"
                        className="upload-list-inline"
                        onPreview={previewImg}
                    >
                        {
                            fileList.length >= 1 ? null :
                                <div>
                                    <Icon type="plus" />
                                    <div className="ant-upload-text">点击上传图片</div>
                                </div>
                        }
                    </Upload>)
                    }
                </FormItem>
                <p style={{ textAlign: 'center' }}>楼层主图尺寸: 375×145</p>
            </Form>
        );
    }
);

//楼层标签
const KeywordFloor = Form.create()(
    (props) => {
        const { form, floorTagName, link, explain } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 }, };
        return (
            <Form layout="vertical">
                <FormItem {...formItemLayout} label="楼层标签" hasFeedback style={{ minHeight: '60px', marginBottom: 0 }}>
                    {getFieldDecorator('floorTagName', {
                        rules: [{ required: true, message: '楼层标签名称不能为空' }],
                    })(
                        <Input type="text" placeholder="请输入楼层标签" />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="链接" hasFeedback style={{ minHeight: '60px', marginBottom: 0 }}>
                    {getFieldDecorator('link', {
                        rules: [{ required: true, message: '链接不能为空' }],
                    })(
                        <Input type="text" placeholder="请输入链接" />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="说明" hasFeedback style={{ minHeight: '60px', marginBottom: 0 }}>
                    {getFieldDecorator('explain', {
                        rules: [{ required: true, message: '说明不能为空' }],
                    })(
                        <Input type="text" placeholder="请输入说明" />
                    )}
                </FormItem>
            </Form>
        );
    }
);


export default class FloorDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileList: [],
            previewVisible: false,
            previewImage: '',
            productvisible: false,
            products: [],
            visible: false,
            KeywordFloor: [],//标签楼层
            isUpdateOrAdd: 0,//0=>更新修改  1=>表示添加
            isUpdatefloorId: 0,//更新修改id
        }
    }
    componentDidMount() {
        if (this.props.params.floorid != "0") {
            $.ajax({
                url: `${config.JuseHomepage}/floorApp/getone?id=${this.props.params.floorid}`,
                type: "get",
                headers: {
                    Authorization: 'Bearer ' + token,
                },
                success: res => {
                    console.log(res)
                    if (res.code === 200) {
                        if (res.data) {
                            const { fileList } = this.state;
                            fileList.push({
                                uid: -1,
                                name: res.data.imgname,
                                status: 'done',
                                url: config.Filepath + res.data.imgname
                            });
                            this.floorForm.setFieldsValue({
                                floorname: res.data.floorname,
                                link: res.data.link,
                                description: res.data.description,
                                Filedata: fileList
                            });
                            const products = [];
                            for (let val of res.data.floorproducts) {
                                products.push(val)
                            }
                            this.setState({
                                products, fileList
                            })
                        }
                    } else {
                        message.error('楼层信息加载失败，请返回重新操作', 2);
                    }
                }
            });
            this.showListKeyword();
        }
    }
    //获取楼层列表
    showListKeyword() {
        $.ajax({
            url: `${config.JuseHomepage}/floorApp/listKeyword`,
            type: "get",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                floorId: this.props.params.floorid
            },
            success: res => {
                if (res.code === 200) {
                    this.setState({
                        KeywordFloor: res.data.rows,
                    });
                    console.log(res);
                }
            }
        });
    }

    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        let isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
            message.config({ top: 50 });
            message.error('您上传的图片大小必须小于10MB！');
        }
        return isIMG && isLt10M;
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //获取表单元素
    saveFloorFormRef(form) {
        this.floorForm = form;
    }
    //获取标签表单元素
    saveKeywordFloor(form) {
        this.KeywordFloor = form;
    }

    //预览图片对话框
    previewImg(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview() {
        this.setState({ previewVisible: false })
    }
    //保存
    saveFloor() {
        this.floorForm.validateFields((err, values) => {
            if (!err) {
                const { products } = this.state;
                let productids = [];
                for (let val of products) {
                    if (val) {
                        productids.push(val.productId)
                    }
                }
                if (productids.length && productids.length <= 8) {
                    let url,
                        data = {
                            floorname: values.floorname,
                            link: values.link,
                            description: values.description,
                            imgname: values.Filedata[0].response ? values.Filedata[0].response.data : values.Filedata[0].name,
                            productids: productids.toString()
                        };
                    if (this.props.params.floorid == "0") {
                        url = `${config.JuseHomepage}/floorApp/save`;
                    } else {
                        url = `${config.JuseHomepage}/floorApp/update`;
                        data.id = this.props.params.floorid;
                    }
                    $.ajax({
                        url: url,
                        type: "post",
                        headers: {
                            Authorization: 'Bearer ' + token,
                        },
                        data: data,
                        success: res => {
                            if (res.code === 200) {
                                window.location.hash = '/floorWx';
                            } else {
                                console.log(res.mes)
                                Modal.warning({
                                    title: '保存失败',
                                    content: `${res.mes}请返回重新操作`,
                                });
                            }
                        }
                    });
                } else {
                    Modal.warning({
                        title: '保存失败',
                        content: `楼层的展示商品最多为8个！`,
                    });
                }
            } else {
                Modal.warning({
                    title: '保存失败',
                    content: `请填写必要的信息，再提交`,
                });
            }
        })
    }
    //添加商品的对话框组件
    addProductModal() {
        if (this.state.products.length >= 8) {
            message.error('添加商品数已达到上限8个，请先删除再添加', 2);
        } else {
            this.setState({
                productvisible: true,
            })
        }
    }
    //确认添加商品
    addProduct(products) {
        this.setState({
            productvisible: false,
            products
        })
    }
    //取消添加商品
    cancelProduct() {
        this.setState({
            productvisible: false
        })
    }
    //移动商品
    moveProduct(index, toindex) {
        const { products } = this.state;
        const item = products[index];
        products[index] = products[toindex];
        products[toindex] = item;
        this.setState({
            products
        })
    }
    //删除商品
    deleteProduct(index) {
        const { products } = this.state;
        products.splice(index, 1)
        this.setState({
            products
        })
    }

    //新增
    showModal() {
        this.setState({
            visible: true,
            isUpdateOrAdd: 1,//添加
        });
    }
    handleOk(e) {
        this.KeywordFloor.validateFields((err, value) => {
            var obj = {};
            for (var key in value) {
                obj[key] = value[key];
            }
            obj.floorId = this.props.params.floorid;
            if (!err) {
                if (this.state.isUpdateOrAdd) {//添加
                    $.ajax({
                        url: `${config.JuseHomepage}/floorApp/addKeyword`,
                        type: "post",
                        headers: {
                            'Authorization': 'Bearer ' + token,
                        },
                        data: obj,
                        success: res => {
                            if (res.code === 200) {
                                this.KeywordFloor.setFieldsValue({
                                    explain: "",
                                    link: "",
                                    floorTagName: "",
                                });
                                this.showListKeyword();
                            }
                        }
                    });
                }
                else {//更新
                    obj.id = this.state.isUpdatefloorId;
                    $.ajax({
                        url: `${config.JuseHomepage}/floorApp/updateKeyword`,
                        type: "post",
                        headers: {
                            'Authorization': 'Bearer ' + token,
                        },
                        data: obj,
                        success: res => {
                            if (res.code === 200) {
                                this.KeywordFloor.setFieldsValue({
                                    explain: "",
                                    link: "",
                                    floorTagName: "",
                                });
                                this.showListKeyword();
                            }
                        }
                    });
                }
                this.setState({
                    visible: false,
                    isUpdateOrAdd: 0,
                });
            }

        });
    }
    handleCancel(e) {
        this.KeywordFloor.setFieldsValue({
            explain: "",
            link: "",
            floorTagName: "",
        });
        this.setState({
            visible: false,
        });

    }
    //删除楼层标签
    floorDelete(text, record) {
        $.ajax({
            url: `${config.JuseHomepage}/floorApp/deleteKeyword`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id: record.id,
            },
            success: res => {
                if (res.code === 200) {
                    this.showListKeyword();
                }
            }
        });
        console.log(record)
    }
    //更新楼层标签
    floorUpdate(text, record) {
        this.setState({
            visible: true,
            isUpdateOrAdd: 0,
            isUpdatefloorId: record.id,
        }, () => {
            this.KeywordFloor.setFieldsValue({
                explain: record.explain,
                link: record.link,
                floorTagName: record.floorTagName,
            });
        });

    }

    render() {
        const columns = [{
            title: '楼层标签名称',
            dataIndex: 'floorTagName',
            width: '25%',
        }, {
            title: '链接',
            dataIndex: 'link',
            width: '25%',
        }, {
            title: '说明',
            dataIndex: 'explain',
            width: '25%',
        }, {
            title: '操作',
            key: 'edit',
            width: '25%',
            render: (text, record) => (
                <span>
                    <a onClick={() => this.floorUpdate(text, record)}>修改</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a onClick={() => this.floorDelete(text, record)}>删除</a>
                </span>
            )
        }];
        return (
            <div className='goods-label zwq_floorclass'>
                <div className='goods-label-cont clearfix'>
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页管理</Breadcrumb.Item>
                            <Breadcrumb.Item>楼层管理</Breadcrumb.Item>
                            <Breadcrumb.Item>新增楼层</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div>
                        <Button onClick={() => window.location.hash = '/floorWx'} style={{ marginRight: 20, float: 'right' }}>返回</Button>
                        <Button onClick={this.saveFloor.bind(this)} className="floor-savebtn">保存</Button>
                    </div>

                    <div className='allgoods-table clearfix'>
                        <div className="floor-msg">
                            {/* 楼层信息表单 */}
                            <FloorForm
                                ref={this.saveFloorFormRef.bind(this)}
                                normFile={this.normFile.bind(this)}
                                beforeUpload={this.beforeUpload.bind(this)}
                                fileList={this.state.fileList}
                                previewImg={this.previewImg.bind(this)}
                            />
                            {/* 预览图片对话框 */}
                            <Modal visible={this.state.previewVisible} footer={null} onCancel={this.cancelPreview.bind(this)} className="wx_floor_imgModel">
                                <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                            </Modal>
                        </div>
                        <div className="floor-products">
                            <p style={{ fontSize: "16px", marginBottom: "5px", marginLeft: "1%" }}>添加商品<Button className='floor-addbtn' width={160} icon="plus" onClick={this.addProductModal.bind(this)}></Button></p>
                            <ul>
                                {
                                    this.state.products.map((item, index) => {
                                        if (item) {
                                            return (<Col span={8} key={index}><li>
                                                <a href={item.imageUrl + item.listImage + '?x-oss-process=image/resize,m_fixed,h_400,w_400'} target='_blank'>
                                                    <img src={item.imageUrl + item.listImage + '?x-oss-process=image/resize,m_fixed,h_200,w_200'} className="floor-pimg" />
                                                </a>
                                                <p>{item.productName}</p>
                                                <div className="floor-pmove">
                                                    {index > 0 && <a onClick={this.moveProduct.bind(this, index, index - 1)} style={{ marginRight: "6%" }}><Icon type="arrow-up" />上移</a>}
                                                    {index < this.state.products.length - 1 && <a onClick={this.moveProduct.bind(this, index, index + 1)} style={{ marginRight: "6%" }}><Icon type="arrow-down" />下移</a>}
                                                    <a onClick={this.deleteProduct.bind(this, index)}><Icon type="close" />删除</a>
                                                </div>
                                            </li></Col>)
                                        }
                                    })
                                }
                            </ul>
                            <FloorProduct
                                visible={this.state.productvisible}
                                products={this.state.products}
                                addProduct={this.addProduct.bind(this)}
                                cancelProduct={this.cancelProduct.bind(this)}
                            />
                        </div>
                    </div>
                    <div className='keyword_pc'>
                        <h1>楼层标签</h1>
                        <div className='allgoods-table clearfix'>
                            <div className='goods-label-tabletr' style={{width:'100%', marginBottom:'20px'}}>
                                <Button className='goods-label-table-app' onClick={this.showModal.bind(this)} width={160} icon="plus">新增</Button>
                            </div>
                            <div className='allgoods-table clearfix'>
                                <Table
                                    className="floor-table"
                                    rowKey="id"
                                    columns={columns}
                                    dataSource={this.state.KeywordFloor}
                                    pagination={false}
                                    bordered
                                />
                            </div>
                            <Modal title="新增" visible={this.state.visible}
                                onOk={this.handleOk.bind(this)}
                                onCancel={this.handleCancel.bind(this)}
                            >
                                <KeywordFloor
                                    ref={this.saveKeywordFloor.bind(this)}
                                />
                            </Modal>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}